<template>
  <div>
    <p>
      直播位置：<span>{{ props.position || '--' }}</span>
    </p>
    <!-- <video ref="videoPlayer" class="video-js"></video> -->
    <LivePlayer
      class="video-js"
      :videoUrl="videoUrl"
      fluent
      autoplay
      live
      stretch
      @error="handleError"
      @message="handleMessage"
      v-if="!isError"
      :controls="false"
    ></LivePlayer>
    <div class="video-js holder" v-else>
      {{ errorText }}
    </div>
  </div>
</template>

<script setup>
  import { onMounted, ref, onUnmounted } from 'vue';
  import { getDeviceVideo } from '@/api/map';
  import LivePlayer from '@liveqing/liveplayer-v3'; // vue3
  import mpegts from 'mpegts.js';
  import videojs from 'video.js';
  // import 'video.js/dist/video-js.min.css'

  let player;
  const playerOption = {
    autoplay: true,
    controls: true,
    sources: [],
  };
  const videoPlayer = ref();
  const props = defineProps({
    position: {
      default() {
        return '--';
      },
    },
    deviceId: {
      required: true,
    },
  });
  const videoUrl = ref('');
  const isError = ref(false);
  const errorText = ref('');

  const dealFlv = () => {
    if (mpegts.getFeatureList().mseLivePlayback) {
      var player = mpegts.createPlayer({
        type: 'flv', // could also be mpegts, m2ts, flv
        isLive: true,
        url: videoUrl.value,
      });
      player.attachMediaElement(videoPlayer.value);
      player.load();
      player.play();
    }
  };

  const dealVideo = () => {
    playerOption.sources.push({
      src: videoUrl.value,
      type: 'application/x-mpegURL',
    });
    player = videojs(videoPlayer.value, playerOption, () => {
      player.log('onPlayerReady');
    });
    player.playsinline(true);
  };

  const handleError = error => {
    console.error(error);
  };

  const handleMessage = message => {
    console.log(message);
    if (message.type !== 'error') return console.log(message);
    isError.value = true;
    errorText.value = message.message;
  };

  onMounted(async () => {
    const res = await getDeviceVideo(props.deviceId);
    if (window.MediaSource) {
      videoUrl.value = res.data.url;
    } else if (!res.data.hlsHd) {
      isError.value = true;
      errorText.value = '暂无可用流';
    } else {
      videoUrl.value = res.data.hlsHd;
    }
    /* if (videoUrl.value.indexOf ('flv') !== -1) {
      dealFlv ()
    } else {
      dealVideo ()
    } */
  });

  onUnmounted(() => {
    /* if (player) {
      player.dispose();
    } */
  });
</script>

<style lang="scss" scoped>

</style>
